package com.gxa.insurance.service.impl;

import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.mapper.InformationMapper;
import com.gxa.insurance.mapper.PolicyMapper;
import com.gxa.insurance.pojo.Information;
import com.gxa.insurance.pojo.Policy;
import com.gxa.insurance.service.PolicyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @date 2022/6/7
 */
@Service("policyService")
@Transactional(rollbackFor = {Throwable.class})
public class PolicyServiceImpl implements PolicyService {

    @Autowired
    PolicyMapper policyMapper;

    @Override
    public Map<String,Object> selectAll() throws BusinessException {

        Map<String,Object> map=new HashMap();
        Integer count = policyMapper.selectAllCount();
        List<Policy> policies = policyMapper.selectAll();

        if(policies.size()==0){
            throw new BusinessException(ExceptionCode.CUSTOMER_IS_EMPTY);
        }
        map.put("count",count);
        map.put("policies",policies);

        return map;
    }

    @Override
    public Policy selectById(Integer id) throws BusinessException {
        Policy policy = policyMapper.selectById(id);

        if (policy==null){
            throw new BusinessException(ExceptionCode.USER_NOT_FONUD);
        }
        return policy;
    }

    @Override
    public List<Policy> selectLikeName(String name) throws BusinessException {

        Policy policy =new Policy();
        policy.setName(name);
        policy.setPhone(name);

        List<Policy> policies = policyMapper.selectLikeName(policy);
        if (policies.size()==0){
            throw new BusinessException(ExceptionCode.USER_NOT_FONUD);
        }
        return policies;
    }

    @Override
    public Integer add(Policy policy) throws BusinessException {

        Integer total = policy.getTotal();
        Integer percentage = policy.getPercentage();

        Integer  integral = total/percentage;

        policy.setIntegral(integral);

        Integer add = policyMapper.add(policy);

        if (add == null){
            throw  new BusinessException(ExceptionCode.INSERT_FILED);
        }

        return add;
    }

    @Autowired
    InformationMapper informationMapper;
    @Override
    public void delete(Integer id) throws BusinessException {

        Policy policy = policyMapper.selectById(id);

        if(policy == null){

            throw new BusinessException(ExceptionCode.DELETE_FILED);
        }

        policyMapper.delete(id);


    }

    @Override
    public void update(Policy policy) {


        policyMapper.update(policy);
    }
}
